import datetime
import os

from apscheduler.schedulers.blocking import BlockingScheduler

import config
import file_utils
import sign_utils
from tencent import Client


def get_service_info():
    return {
        "ServiceEdition": "basic",
        "CallbackUrl": "https://baidu.com",
        "SubmitSource": "RDM-rdm",
    }


def upload_app(config: config.Config()) -> dict:
    directory = os.path.dirname(os.path.abspath(__file__))
    directory_path = os.path.join(directory,
                                  f"{config.get_app_info()['app_version_code']}-{config.get_app_info()['app_version_name']}")
    status, path = file_utils.get_file_md5(config.get_app_info()['apk_download_path'], save_path=directory_path)
    if status:
        md5 = file_utils.md5(path)
        return {
            "AppUrl": config.get_app_info()['apk_download_path'],
            "AppMd5": md5
        }
    return None


def find_data(task_id: str):
    result = app.find_result({"ItemId": task_id})
    print(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} 正在扫描加固任务，请稍后......状态：【{'加固完成' if result['TaskStatus']==1 else '加固中'}】")
    if result and result['TaskStatus'] == 1:
        # 取消定时任务
        sched.pause()
        # 下载加固包
        print("正在下载加固包......")
        file_name = f"{config.get_app_info()['app_version_code']}-{config.get_app_info()['app_version_name']}"
        path = f"{os.path.join(config.base_dir, file_name)}"
        status, file_path = file_utils.download(result['ShieldInfo']['AppUrl'], path, "jiagu.apk")
        if status:
            print("下载加固包成功")
            if sign_utils.resource_zip(file_path, f"{os.path.join(path, 'jiagu-zipalign.apk')}"):
                print("开始生成渠道包")
                apk_path = f"{os.path.join(path, 'jiagu-zipalign.apk')}"
                path = sign_utils.channel_create(f"{os.path.join(path, 'jiagu-zipalign.apk')}")
                if path:
                    print("渠道包生成成功")
                    sched.pause()
                    sign_utils.sign_app(os.listdir(path), path, apk_path)
                else:
                    print("渠道包生成失败")
        else:
            print("下载加固包失败")


app = Client()
sched = BlockingScheduler()
# 读取配置信息
config = config.Config()
# 上传APP

print("正在下载安装包......")
params = {
    "AppInfo": upload_app(config),
    "ServiceInfo": get_service_info()
}
upload_result = app.pin_up(params)
if upload_result['Progress'] and upload_result['Progress'] == 2:
    # 开启定时任务
    sched.add_job(func=find_data, args=[upload_result['ItemId']], trigger="interval", seconds=5)
sched.start()
